﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System.Threading.Tasks;

namespace DannyFramework.Results
{
    /// <summary>
    /// 通用结果过滤器
    /// </summary>
    public class CommonResultFilter : IAsyncResultFilter
    {
        /// <summary>
        /// 拦截返回，进行统一包装
        /// </summary>
        /// <param name="context"></param>
        /// <param name="next"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next)
        {
            //实现统一包装
            if (context.Result is ObjectResult objectResult)
            {
                int? StatusCode = objectResult.StatusCode;
                if (StatusCode == 200
                    || StatusCode == 201
                    || StatusCode == 202
                    || !StatusCode.HasValue)
                {
                    //统一包装正常结果（单个数据或集合数据）
                    objectResult.Value = WrapSuccessResult(objectResult.Value);
                }
            }
            await next(); //next() 执行下一个过滤器
        }

        private object WrapSuccessResult(object result)
        {
            //创建统一结果
            CommonResult commonResult = new CommonResult();
            commonResult.Code = 0;
            commonResult.Message = "操作成功";

            //获取结果并输出
            if (result.GetType().Name.Contains("List"))
                //转换成list结果
                commonResult.Result = new JsonResult(result).Value;
            else
                //转换为单个结果
                commonResult.Result = new JsonResult(result).Value;

            return commonResult;
        }
    }
}
